using Microsoft.Extensions.Configuration;
using microsoft_TODO.Models;
using MongoDB.Bson;
using MongoDB.Driver;

namespace microsoft_TODO.MongoCore.Repositories {
    public class ListRepository : BaseRepository<CheckList<Task>>, IListRepository {
        public ListRepository (IConfiguration configuration) : base (configuration, "list") { }

        public bool RemoveTaskViaIndexOfArray (string lid, int index) {
            // * to remove the data(is a object but not include a _id identity) in a array object(tasks):
            // * turn the data to null and then remove the null
            var objectId = new BsonObjectId (ObjectId.Parse (lid));
            var filter = new BsonDocument { { "_id", objectId } };
            // * to remove the data that's subscript is equal to the number:
            // * #1 db.list.update({_id: objectId},{$unset:{tasks.number, 1}})
            var updateUnset = new BsonDocument {
                {
                "$unset",
                new BsonDocument ("tasks." + index, 1)
                }
            };
            var resUnset = this.BsonCollection.UpdateOne (filter, updateUnset);
            // * #2 db.list.update({_id: objectId},{$pull:{tasks:null}})
            if (resUnset.ModifiedCount == 1) {
                var updatePullNull = new BsonDocument {
                    {
                        "$pull",
                        new BsonDocument ("tasks", BsonNull.Value)
                    }
                };
                var resPullNull = this.BsonCollection.UpdateOne(filter, updatePullNull);
                if (resPullNull.ModifiedCount > 0)
                    return true;
            }
            return false;
        }

        public bool UpdateTaskViaIndexOfArray(string lid, int index, string prop, BsonValue value) {
            var objectId = new BsonObjectId (ObjectId.Parse(lid));
            var filter = new BsonDocument { { "_id", objectId} };
            var updateSet = new BsonDocument {
                {
                    "$set",
                    new BsonDocument ($"tasks.{index}.{prop}", value)
                }
            };
            var resSet = this.BsonCollection.UpdateOne(filter, updateSet);
            return resSet.ModifiedCount == 1 ? true : false;
        }
    }
}